import asyncio
import json
from datetime import datetime
import re
from typing import List, Dict, Any, Optional
from openai import AsyncOpenAI
from app.schemas.system.copywriting import ContentType, ContentStyle, GenerateRequest, CopywritingResponse
from app.core.config import settings
from app.utils.app_log import logger


class CopywritingService:
    """基于OpenAI的文案生成服务"""
    
    def __init__(self):
        self.client = AsyncOpenAI(
            api_key=settings.openai_api_key,
            base_url=settings.openai_base_url
        )
        logger.info(f"初始化 {settings.openai_base_url} {settings.openai_model}")
        self.scene_prompts = self._init_scene_prompts()
        self.style_prompts = self._init_style_prompts()
    
    def _init_scene_prompts(self) -> Dict[ContentType, str]:
        """初始化场景提示词"""
        return {
            ContentType.DAILY: "生成关于日常生活的文案，要体现生活的美好和小确幸，适合朋友圈分享",
            ContentType.MOOD: "生成表达心情感悟的文案，要有情感共鸣，能够触动人心",
            ContentType.FOOD: "生成美食相关的文案，要体现美食的诱人和生活的幸福感",
            ContentType.TRAVEL: "生成旅行相关的文案，要体现对远方的向往和旅途的美好",
            ContentType.WORK: "生成工作感悟的文案，要积极正能量，体现职场奋斗和成长",
            ContentType.LOVE: "生成情感表达的文案，要温馨浪漫，适合表达爱意和友情",
            ContentType.INSPIRATION: "生成励志正能量的文案，要激发人的斗志和向上的力量"
        }
    
    def _init_style_prompts(self) -> Dict[ContentStyle, str]:
        """初始化风格提示词"""
        return {
            ContentStyle.WARM: "语调温暖治愈，用词温馨暖心，让人感到被关怀",
            ContentStyle.HUMOR: "语调轻松幽默，适当使用俏皮话，让人会心一笑",
            ContentStyle.LITERARY: "语调文艺清新，用词优美典雅，有一定的文学性",
            ContentStyle.SIMPLE: "语调简约自然，用词朴实简洁，贴近生活",
            ContentStyle.ELEGANT: "语调优雅精致，用词高雅有品味，体现生活质感",
            ContentStyle.POETIC: "语调诗意浪漫，用词富有韵律感，充满想象力"
        }
    
    async def generate_copywriting(self, request: GenerateRequest) -> List[CopywritingResponse]:
        """使用OpenAI生成文案"""
        try:
            # 构建提示词
            prompt = self._build_prompt(request)
            # 调用OpenAI API
            logger.info(f"调用 {settings.openai_base_url} 使用模型 {settings.openai_model} 生成文案")
            response = await self.client.chat.completions.create(
                model=settings.openai_model,
                messages=[
                    {
                        "role": "system",
                        "content": "你是一个专业的文案创作专家，擅长创作高质量、有文化内涵的社交媒体文案。你的文案要避免中二、俗套，要有深度和美感。"
                    },
                    {
                        "role": "user",
                        "content": prompt
                    }
                ],
                max_tokens=settings.openai_max_tokens,
                temperature=settings.openai_temperature,
                n=1
            )
        
            # 解析响应
            generated_text = response.choices[0].message.content.strip()
            copywritings = self._parse_generated_text(generated_text, request)
            
            return copywritings
            
        except Exception as e:
            # 如果API调用失败，使用备用方案
            # print(f"OpenAI API调用失败: {e}")
            return self._generate_fallback_copywriting(request)
    
    def _build_prompt(self, request: GenerateRequest) -> str:
        """构建OpenAI提示词"""
        scene_prompt = self.scene_prompts.get(request.content_type, "")
        style_prompt = self.style_prompts.get(request.style, "")
        
        keywords_text = ""
        if request.keywords:
            keywords_text = f"\n关键词要求：请在文案中巧妙融入这些关键词：{', '.join(request.keywords)}"
        
        prompt = f"""请根据以下要求创作3-5条高质量的文案：

场景要求：{scene_prompt}
风格要求：{style_prompt}{keywords_text}

创作要求：
1. 每条文案控制在{request.length or 50}字以内
2. 文案要有文化内涵，避免俗套和中二
3. 适合在朋友圈或抖音等社交平台分享
4. 用词优雅，有美感和深度
5. 可以适当使用表情符号增加趣味性
6. 每条文案另起一行，用"---"分隔

请开始创作："""
        
        return prompt
    
    def _parse_generated_text(self, text: str, request: GenerateRequest) -> List[CopywritingResponse]:
        """解析生成的文案文本"""
        copywritings = []
        logger.info(F"响应 {text}")
        pattern = r'<\s*think\s*>\s*(.*?)\s*<\s*/\s*think\s*>'
        text = re.sub(pattern, '', text, flags=re.DOTALL | re.IGNORECASE)
        # 按分隔符分割文案
        texts = [t.strip() for t in text.split('---') if t.strip()]
        logger.info(f"清洗后{texts}")
        # 如果没有分隔符，按换行符分割
        if len(texts) <= 1:
            texts = [t.strip() for t in text.split('\n') if t.strip() and len(t.strip()) > 10]
        
        for text in texts[:5]:  # 最多取5条
            if text:
                copywriting = CopywritingResponse(
                    content=text,
                    content_type=request.content_type,
                    style=request.style,
                    created_at=datetime.now().isoformat()
                )
                copywritings.append(copywriting)
        
        # 如果解析结果为空，创建一条默认文案
        if not copywritings:
            copywriting = CopywritingResponse(
                content=text[:100] + "..." if len(text) > 100 else text,
                content_type=request.content_type,
                style=request.style,
                created_at=datetime.now().isoformat()
            )
            copywritings.append(copywriting)
        
        return copywritings
    
    def _generate_fallback_copywriting(self, request: GenerateRequest) -> List[CopywritingResponse]:
        """备用文案生成方案"""
        fallback_templates = {
            ContentType.DAILY: ["今日份的小美好，让生活多了几分温暖 ☀️", "在平凡的日子里，发现不平凡的快乐 ✨"],
            ContentType.MOOD: ["心境如水，澄澈而宁静 🌊", "愿你的心情，如春风般温暖 🌸"],
            ContentType.FOOD: ["人间烟火气，最抚凡人心 🍜", "美食如诗，温暖如家 🏠"],
            ContentType.TRAVEL: ["世界那么大，心向远方 🌍", "在路上，遇见更好的自己 🚶‍♂️"],
            ContentType.WORK: ["每一份努力，都值得被看见 💪", "在奋斗的路上，做最好的自己 ⭐"],
            ContentType.LOVE: ["爱如春风，温柔而美好 💕", "因为有你，世界变得温柔 🌹"],
            ContentType.INSPIRATION: ["向阳而生，逐光而行 🌟", "每一天都是新的开始 🌅"]
        }
        
        templates = fallback_templates.get(request.content_type, ["生活如诗，岁月如歌 🎵"])
        
        copywritings = []
        for template in templates:
            copywriting = CopywritingResponse(
                content=template,
                content_type=request.content_type,
                style=request.style,
                created_at=datetime.now().isoformat()
            )
            copywritings.append(copywriting)
        
        return copywritings